package se.webbzon.oschi01.utilities;

public class StringUtils {
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Divides string by adding newline characters so that each
	 * line is maximal maxLength characters. **/
	public static String divide(String str, int maxLength) {
		StringBuilder builder = new StringBuilder();
		divideInner(str,builder,0,maxLength);
		return builder.toString();
	}
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Inner help function to divide. **/
	private static void divideInner(String str, StringBuilder result, int start, int maxLength) {
		if (str.length() - start <= maxLength)
			result.append(str.substring(start));
		else {
			int lastSpace = start;
			for (int i = start; i < str.length(); i++) {
				int length = i - start;
				if (str.charAt(i) == ' ') {
					if (length > maxLength) {
						result.append(str.substring(start, lastSpace) + "\n");
						divideInner(str,result,lastSpace+1,maxLength);
						return;
					} else
						lastSpace = i;
				}
			}
			result.append(str.substring(start, lastSpace) + "\n");
			divideInner(str,result,lastSpace+1,maxLength);
		}
	}

}
